{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="data:,">
    <title>注册账号</title>
    <link rel="stylesheet" href="{% static 'css/register.css' %}">
</head>
<body>
    <div class="register-container">
        <h1>注册账号</h1>
        <form id="register-form">
            {% csrf_token %}
            <input type="text" placeholder="用户名" name="user_name" id="user_name" value="{{ user_name|default:'' }}" required>
            <input type="text" placeholder="账号" name="user_no" id="user_no" value="{{ user_no|default:'' }}" required>
            <input type="password" placeholder="密码" name="password" id="password" value="{{ password|default:'' }}" required>
            <button type="submit">确定</button>
        </form>
        <button type="button" id="back-button">返回登录</button>
        {% if error %}
        <p style="color: rgba(255, 0, 0, 0.808);">{{ error }}</p>
        {% endif %}
    </div>
    <script>
        // 返回登录
        document.getElementById('back-button').addEventListener('click', function () {
            window.location.href = '/';
        });
        // 注册
        document.getElementById('register-form').addEventListener('submit', function (event) {
            event.preventDefault();
            var userName = document.getElementById('user_name').value;
            var userNo = document.getElementById('user_no').value;
            var password = document.getElementById('password').value;
            if (!userName || !userNo || !password) 
            {
                event.preventDefault();
                alert('请填写所有字段');
            }
            fetch('/api/user/', {
                method: 'POST',
                body: JSON.stringify({
                    user_id: userNo,
                    pwd: password,
                    user_name: userName
                }),
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}'
                }
            })
            .then(response => {
                if (response.ok) {
                    window.location.href = '/';
                } else {
                    return response.json().then(data => {
                        alert(data.message);
                    });
                }
            })
        });
    </script>
</body>
</html>